// 新版宿舍数据生成脚本
// 此脚本将直接生成符合用户需求的宿舍数据并保存到localStorage

// 检查是否在浏览器环境中运行
const isBrowser = typeof window !== 'undefined' && typeof localStorage !== 'undefined';

if (!isBrowser) {
  console.log('此脚本需要在浏览器环境中运行');
  // 提供备用代码，用于在服务器端运行时提示
  if (typeof module !== 'undefined') {
    module.exports = {
      generateDormitories: function() {
        console.log('请在浏览器中运行此脚本以生成宿舍数据');
        return [];
      }
    };
  }
}

// 生成宿舍数据
function generateDormitories() {
  console.log('开始生成新版宿舍数据...');
  const dormitories = [];
  let dormitoryId = 1;
  
  // 生成随机入住人数
  const getRandomOccupancy = (capacity) => Math.floor(Math.random() * (capacity + 1));
  // 生成时间戳
  const getCurrentTime = () => new Date().toISOString();

  // 1. 生成学四舍数据（女生宿舍）
  console.log('正在生成学四舍数据...');
  // 学四舍每层的专业分配
  const xuesisheFloors = [
    { floor: 1, specialty: '新生女生宿舍' },
    { floor: 2, specialty: '元宇宙女生宿舍' },
    { floor: 3, specialty: '鸿蒙生态开发女生宿舍' },
    { floor: 4, specialty: '云计算女生宿舍' },
    { floor: 5, specialty: '数智传媒女生宿舍' },
    { floor: 6, specialty: '人工智能女生宿舍' }
  ];
  
  xuesisheFloors.forEach(item => {
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '学四舍',
        roomNumber: `${item.floor}${String(roomNum).padStart(2, '0')}`, // 格式：101, 102...
        type: 'female',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: item.floor,
        status: 'active',
        notes: item.specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  });

  // 2. 生成学三舍数据（男生宿舍）
  console.log('正在生成学三舍数据...');
  // 学三舍楼层分配：1-3层是元宇宙，4-6层是鸿蒙生态开发
  for (let floor = 1; floor <= 6; floor++) {
    const specialty = floor <= 3 ? '元宇宙男生宿舍' : '鸿蒙生态开发男生宿舍';
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '学三舍',
        roomNumber: `${floor}${String(roomNum).padStart(2, '0')}`, // 格式：101, 102...
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  // 3. 生成皇悦三期数据（男生宿舍）
  console.log('正在生成皇悦三期数据...');
  // 皇悦三期：人工智能和云计算男生宿舍，宿舍号93开头，每层5个宿舍
  for (let floor = 1; floor <= 6; floor++) {
    const specialty = floor <= 3 ? '人工智能男生宿舍' : '云计算男生宿舍';
    for (let roomNum = 1; roomNum <= 5; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '皇悦三期',
        roomNumber: `93${floor}${String(roomNum).padStart(2, '0')}`, // 格式：9301, 9302...
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  // 4. 生成皇悦一期数据（男生宿舍）
  console.log('正在生成皇悦一期数据...');
  // 皇悦一期：数智传媒男生宿舍，宿舍号91开头，每层10个宿舍
  for (let floor = 1; floor <= 6; floor++) {
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '皇悦一期',
        roomNumber: `91${floor}${String(roomNum).padStart(2, '0')}`, // 格式：9101, 9102...
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: '数智传媒男生宿舍',
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  return dormitories;
}

// 清除现有数据并保存新数据
function saveDormitories() {
  if (!isBrowser) {
    console.log('无法访问localStorage，数据未保存');
    return false;
  }
  
  try {
    // 清除现有数据
    console.log('清除现有宿舍数据...');
    localStorage.removeItem('dormitoryStorage');
    
    // 清除学生的宿舍关联
    const studentsJson = localStorage.getItem('studentStorage');
    if (studentsJson) {
      const students = JSON.parse(studentsJson);
      const updatedStudents = students.map(student => ({
        ...student,
        dormitoryId: undefined
      }));
      localStorage.setItem('studentStorage', JSON.stringify(updatedStudents));
      console.log('已清除所有学生的宿舍关联');
    }
    
    // 生成并保存新数据
    const newDormitories = generateDormitories();
    localStorage.setItem('dormitoryStorage', JSON.stringify(newDormitories));
    
    console.log(`✓ 宿舍数据生成完成！共生成 ${newDormitories.length} 个宿舍`);
    
    // 显示统计信息
    const buildings = [...new Set(newDormitories.map(d => d.building))];
    console.log('生成的楼栋列表：');
    buildings.forEach(building => {
      const count = newDormitories.filter(d => d.building === building).length;
      const gender = building === '学四舍' ? '女生' : '男生';
      console.log(`- ${building}（${gender}宿舍）: ${count} 个宿舍`);
    });
    
    // 显示各专业分布
    console.log('\n专业分布情况：');
    const specialties = [...new Set(newDormitories.map(d => d.notes))];
    specialties.forEach(specialty => {
      const count = newDormitories.filter(d => d.notes === specialty).length;
      console.log(`- ${specialty}: ${count} 个宿舍`);
    });
    
    return true;
  } catch (error) {
    console.error(`✗ 保存数据失败: ${error.message}`);
    return false;
  }
}

// 如果在浏览器环境中，直接执行
if (isBrowser) {
  // 创建一个简单的HTML结构来显示进度
  const createProgressUI = () => {
    const div = document.createElement('div');
    div.style.position = 'fixed';
    div.style.top = '20px';
    div.style.left = '50%';
    div.style.transform = 'translateX(-50%)';
    div.style.padding = '20px';
    div.style.backgroundColor = '#f0f0f0';
    div.style.border = '1px solid #ccc';
    div.style.borderRadius = '8px';
    div.style.zIndex = '9999';
    div.style.maxWidth = '600px';
    div.style.fontFamily = 'Arial, sans-serif';
    
    div.innerHTML = `
      <h2>宿舍数据生成工具</h2>
      <div id="progress" style="margin: 10px 0;"></div>
      <pre id="logs" style="background-color: #222; color: #0f0; padding: 10px; border-radius: 4px; max-height: 300px; overflow: auto;"></pre>
    `;
    
    document.body.appendChild(div);
    
    // 重写console.log，使其同时输出到页面和控制台
    const originalConsoleLog = console.log;
    const logsElement = document.getElementById('logs');
    
    console.log = function(message) {
      originalConsoleLog.apply(console, arguments);
      if (logsElement) {
        const logLine = document.createElement('div');
        logLine.textContent = message;
        logsElement.appendChild(logLine);
        logsElement.scrollTop = logsElement.scrollHeight;
      }
    };
    
    // 更新进度显示
    document.getElementById('progress').textContent = '正在生成宿舍数据...';
  };
  
  // 确保DOM已加载
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      createProgressUI();
      setTimeout(() => {
        const success = saveDormitories();
        if (success) {
          document.getElementById('progress').textContent = '宿舍数据生成成功！请刷新页面查看';
          document.getElementById('progress').style.color = 'green';
        } else {
          document.getElementById('progress').textContent = '宿舍数据生成失败，请检查控制台';
          document.getElementById('progress').style.color = 'red';
        }
      }, 100);
    });
  } else {
    createProgressUI();
    setTimeout(() => {
      const success = saveDormitories();
      if (success) {
        document.getElementById('progress').textContent = '宿舍数据生成成功！请刷新页面查看';
        document.getElementById('progress').style.color = 'green';
      } else {
        document.getElementById('progress').textContent = '宿舍数据生成失败，请检查控制台';
        document.getElementById('progress').style.color = 'red';
      }
    }, 100);
  }
}

// 导出函数，以便在其他地方调用
if (typeof module !== 'undefined') {
  module.exports = {
    generateDormitories,
    saveDormitories
  };
}

// 备用代码块：如果以上代码无法在浏览器中正确执行，
// 请将下面的代码复制到浏览器控制台中执行

/*
// 备用代码 - 复制到浏览器控制台执行
(function() {
  console.log('开始生成新版宿舍数据...');
  const dormitories = [];
  let dormitoryId = 1;
  
  const getRandomOccupancy = (capacity) => Math.floor(Math.random() * (capacity + 1));
  const getCurrentTime = () => new Date().toISOString();

  // 1. 生成学四舍数据（女生宿舍）
  const xuesisheFloors = [
    { floor: 1, specialty: '新生女生宿舍' },
    { floor: 2, specialty: '元宇宙女生宿舍' },
    { floor: 3, specialty: '鸿蒙生态开发女生宿舍' },
    { floor: 4, specialty: '云计算女生宿舍' },
    { floor: 5, specialty: '数智传媒女生宿舍' },
    { floor: 6, specialty: '人工智能女生宿舍' }
  ];
  
  xuesisheFloors.forEach(item => {
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '学四舍',
        roomNumber: `${item.floor}${String(roomNum).padStart(2, '0')}`,
        type: 'female',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: item.floor,
        status: 'active',
        notes: item.specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  });

  // 2. 生成学三舍数据（男生宿舍）
  for (let floor = 1; floor <= 6; floor++) {
    const specialty = floor <= 3 ? '元宇宙男生宿舍' : '鸿蒙生态开发男生宿舍';
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '学三舍',
        roomNumber: `${floor}${String(roomNum).padStart(2, '0')}`,
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  // 3. 生成皇悦三期数据（男生宿舍）
  for (let floor = 1; floor <= 6; floor++) {
    const specialty = floor <= 3 ? '人工智能男生宿舍' : '云计算男生宿舍';
    for (let roomNum = 1; roomNum <= 5; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '皇悦三期',
        roomNumber: `93${floor}${String(roomNum).padStart(2, '0')}`,
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: specialty,
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  // 4. 生成皇悦一期数据（男生宿舍）
  for (let floor = 1; floor <= 6; floor++) {
    for (let roomNum = 1; roomNum <= 10; roomNum++) {
      dormitories.push({
        id: `dorm-${dormitoryId++}`,
        building: '皇悦一期',
        roomNumber: `91${floor}${String(roomNum).padStart(2, '0')}`,
        type: 'male',
        capacity: 8,
        currentOccupancy: getRandomOccupancy(8),
        students: [],
        floor: floor,
        status: 'active',
        notes: '数智传媒男生宿舍',
        createdAt: getCurrentTime(),
        updatedAt: getCurrentTime()
      });
    }
  }

  // 清除现有数据
  localStorage.removeItem('dormitoryStorage');
  
  // 清除学生的宿舍关联
  const studentsJson = localStorage.getItem('studentStorage');
  if (studentsJson) {
    const students = JSON.parse(studentsJson);
    const updatedStudents = students.map(student => ({
      ...student,
      dormitoryId: undefined
    }));
    localStorage.setItem('studentStorage', JSON.stringify(updatedStudents));
  }
  
  // 保存新数据
  localStorage.setItem('dormitoryStorage', JSON.stringify(dormitories));
  
  console.log(`宿舍数据生成完成！共生成 ${dormitories.length} 个宿舍`);
  console.log('请刷新页面查看新数据');
})();
*/